package org.seckill.service.impl;

import org.apache.commons.collections.MapUtils;
import org.seckill.dao.SeckillDao;
import org.seckill.dao.SuccessKilledDao;
import org.seckill.dto.Expose;
import org.seckill.dto.SeckillExecution;
import org.seckill.dto.cache.RedisDao;
import org.seckill.entity.Seckill;
import org.seckill.entity.SuccessKilled;
import org.seckill.enums.SeckillStatEnum;
import org.seckill.exception.RepeaKillException;
import org.seckill.exception.SeckillCloseException;
import org.seckill.exception.SeckillException;
import org.seckill.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;


import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Component @Service @DAO @Controller
 */
@Service
@Transactional
/**
  *使用注解控制事务方法的优点：
 * 1：开发团队打成一致约定，明确标注事务方法的编程风格。
 * 2：保证事务方法的执行时间尽可能短，不要穿插其他的网络操作，RPC/HTTP请求（缓存之类的）或者玻璃事务方法外。
 * 3：不是所有方法都需要事务，如只有一条修改操作，或者只读操作不需要事务控制。
 * *
 */
public class SeckillServiceImpl implements SeckillService{

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    //注入Service 依赖
    @Autowired //@Resource
    private SeckillDao seckillDao;
    @Autowired
    private SuccessKilledDao successKilledDao;

    //md5盐值字符串，用于混淆MD5
    private final String slat = "asdqwxcas12,3.1/23,;q;lekl;3k4l;1123l;12q.wem,.ma/.d,a.d,lq;wkel2l;123;l";

    @Autowired
    private RedisDao redisDao;
    public List<Seckill> getSeckillList() {

        return seckillDao.queryAll(0,10);
    }

    public Seckill getById(long seckillId) {
        return seckillDao.queryById(seckillId);
    }

    public Expose exportSeckillUrl(long seckillId) {

        //redis缓存起来;超时的基础维护一致性
        //1:访问redis
        Seckill seckill = redisDao.getSeckill(seckillId);
        if (seckill == null){
        //2:访问数据库
            seckill = seckillDao.queryById(seckillId);
            if (seckill == null) {
                return new Expose(false, seckillId);
            }else {
                //3:放入redis
                redisDao.putSeckill(seckill);
            }
        /**
         * get from cache
         *  get db
         *  else
         *      put cache
         *  locgion
         *
         */
        }
        Date startTime = seckill.getStartTime();
        Date endTime = seckill.getEndTime();

        //系统当前时间
        Date nowTime = new Date();
        if (nowTime.getTime() < startTime.getTime() || nowTime.getTime() > endTime.getTime()) {
            return new Expose(false, seckillId, nowTime.getTime(), startTime.getTime(), endTime.getTime());
        }
        //转化特定字符串的过程,不可逆
        String md5 = this.getMD5(seckillId) ; //TODO
        return new Expose(true,md5,seckillId);
    }

    private String getMD5(long seckillId){
        String base = seckillId + "/" + slat;
        String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
        return md5;
    }

    public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5) throws SecurityException, RepeaKillException, SeckillCloseException {

        if(md5 == null || !md5.equals(this.getMD5(seckillId))){
            throw new SeckillException("seckill data rewrite");
        }

        //执行秒杀逻辑:减库存 + 记录购买行为
        try {
            Date nowTime = new Date();

            //减库存
            int insertCount = successKilledDao.insertSuccessKilled(seckillId,userPhone);
            //唯一：seckillId,userPhone
            if (insertCount <= 0){
                //重复秒杀
                throw  new RepeaKillException("seckill repeated");
            }else {
                //秒杀成功
                //秒杀成功,得到成功插入的明细记录,并返回成功秒杀的信息 commit
                int updateCount = seckillDao.reduceNumber(seckillId,nowTime);
                if (updateCount <= 0){
                    //没有更新到记录，秒杀结束
                    throw  new SeckillCloseException("seckill is closed");
                }else {
                    //减库存成功
                    //记录购买成功
                    SuccessKilled successKilled=successKilledDao.queryByIdWithSeckill(seckillId,userPhone);
                    SeckillExecution execution = new SeckillExecution(seckillId, SeckillStatEnum.SUCCESS,successKilled);

                    return execution;
                }



            }



        }catch (SeckillCloseException e1){
            throw e1;
        }catch (RepeaKillException e2){
            throw e2;
        }catch (Exception e) {
            logger.error(e.getMessage(),e);
            //所有编译器异常，转化为运行期异常
            throw new SeckillException("seckill inner error:"+e.getMessage());
        }

    }

    public SeckillExecution executeSeckillProcedure(long seckillId, long userPhone, String md5){
        if (md5 == null || ! md5.equals(getMD5(seckillId))){

            return new SeckillExecution(seckillId,SeckillStatEnum.DATA_REWRITE);
        }
        Date killTime = new Date();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("seckillId",seckillId);
        map.put("phone",userPhone);
        map.put("killTime",killTime);
        map.put("result",null);
        //执行存储过程，result被复制
        try {

            seckillDao.killByProcedure(map);
            //获取result

            int result = MapUtils.getInteger(map,"result",-2);

            if (result == 1){
                SuccessKilled sk = successKilledDao.
                        queryByIdWithSeckill(seckillId,userPhone);

                return new SeckillExecution(seckillId,SeckillStatEnum.SUCCESS,sk);
            }else {

                return new SeckillExecution(seckillId,SeckillStatEnum.stateOf(result));
            }
        } catch (Exception e) {

            logger.error(e.getMessage(),e);
            return new SeckillExecution(seckillId,SeckillStatEnum.INNER_ERROR);
        }

    }
}
